import React, { useEffect, useRef, useState,forwardRef, useImperativeHandle}  from "react";
import { withRouter } from "react-router-dom";
import commonConfig from 'static/js/commonConfig'
import { connect } from 'react-redux'
import {queryByIdVideoPublish,queryByIdVideo,editVideoStatus,setRemark,addVideo,getHistoryRemark} from 'api/index'
import {notification,PageHeader, Button, Modal,Steps,Tabs,Form,Select,Cascader,Spin,Alert, message,Tag} from 'antd'
import {checkDraftData} from 'redux/action'
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm'
import  VideoUpload  from 'components/Upload/video'
import  UploadSrt  from 'components/Upload/srt'
import  UploadPicture  from 'components/Upload/index'

const { SHOW_CHILD } = Cascader;
const { TabPane } = Tabs;
const { Step } = Steps;

// 获取页面操作的权限  获取状态切换的权限 获取对应的值 
const {getPageJurisdiction,getStatusJurisdiction,statusValue,getStatusIndex} = commonConfig

// 头部
const LlxHead = forwardRef((props, ref) => {

  const {form,userName,role,examineStatus} = props

  const formItem  = form.getFieldValue()

  useImperativeHandle(ref, () => ({
    current
  }));

  const [current,setCurrent] = useState(getStatusIndex(formItem.videoStatus))

  const changeStatus = (current) => {
    const data = getStatusJurisdiction(formItem.videoStatus,formItem.createBy,formItem.rmanager,formItem.qmanager,userName,role)

    if(!data.includes(statusValue(current,formItem.videoStatus))) {
      const text = data.length?data.join(' + '):'无'
      notification.error({
        message: '不可切换该状态，你当前可选择得状态:' + text,
        description: '操作人：' + userName,
        duration:2
      });
      return
    }
    setCurrent(current)
  }

  return <div className="head-info">
    
    <PageHeader
      ghost={false}
      title={formItem.videoName}
      subTitle={<div>创建人 : {formItem.createBy} &nbsp;&nbsp;更新人 : {formItem.updateBy}<br></br>负责人 : {formItem.rmanager||formItem.qmanager||'无'} &nbsp;&nbsp;更新时间 : {formItem.updateTime}</div>}
      extra={!examineStatus?[
        <Button key="2" onClick={props.getMore}>更多信息</Button>,
        <Button key="1" type="primary" onClick={props.preservationData}>
          保存
        </Button>,
      ]:[<Button key="2" onClick={props.getMore}>更多信息</Button>]}
    >
          {
       examineStatus?<div className="info-status">
         {form.getFieldValue().upperLower===1010?<Tag color="success">发布状态</Tag>:(form.getFieldValue().upperLower===1000?<Tag color="error">已下架</Tag>:<Tag color="error">未知</Tag>)}
       </div>:''
    }
    {
       !examineStatus?<div className="head-status">
        {
          ['N','R','Q'].includes(formItem.videoStatus)?(
           <Steps style={{width:'400px',marginTop:'22px'}}  current={current} onChange={changeStatus}>
           <Step title="N" />
           <Step title="R" />
           <Step title="Q" />
           <Step title="P" />
         </Steps>
          ):(
           <Steps style={{width:'400px',marginTop:'22px'}}  current={current} onChange={changeStatus}>
           <Step title="PN" />
           <Step title="PR" />
           <Step title="PQ" />
           <Step title="P" />
         </Steps>
          )
        }
       </div>:''
    }
       
    
    </PageHeader>
  </div>
})
// 查看更多弹框
const LookMore = (props) => {
  const {isModalVisible, setIsModalVisible} = props

  const id = window.location.href.slice(window.location.href.indexOf('id=')+3)

  useEffect(()=>{
    isModalVisible&&getHistoryList()

  },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps

  
 //分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:10
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(0)
//表头配置信息
const columns = [
      {title: '状态变更', dataIndex: 'statusNext', key: 'statusNext', align: 'center',render:(text,row)=>{
        return <div>
        {row.statusNow} → {row.statusNext}
        </div>
      }},
      {title: '留言', dataIndex: 'remark', key: 'remark', align: 'center'},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center'},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center'}
]
 
 
 const handleCancel = () => {
    setIsModalVisible(false);
 };

 const getHistoryList = async(value) => {
  setLoading(true)
  const res = await getHistoryRemark({ id: id, type:'VIDEO', currPage:value&&value.pageSize?value.current:pagination.current,
  pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize})
  setDataSource(res.result.records)
  setTotal(res.result.total)
  setLoading(false)
 }


 function callback(key) {
  console.log(key);
}

return   <Modal wrapClassName='get-more' width={800} title="查看更多" visible={isModalVisible} footer={null} onCancel={handleCancel}>
         <Tabs defaultActiveKey="1" onChange={callback}>
          <TabPane tab="历史记录" key="1">
           {/* 表格 */}
             <LlxTable
              loading={loading} 
              pagination={pagination}
              setPagination={setPagination}
              selectedRowShow={false}
              height={500}
              total={total}
              getNewList={getHistoryList}
              columns={columns}
              dataSource={dataSource}/>
          </TabPane>
         </Tabs>
 </Modal>
}
// 视频详情
const VideoMain = (props) => {

  const {form,dictionaries,disabled} = props
  const newItem = [
    {label: '视频名称',type:'input', name: 'videoName' , span: 12 ,rules:[
      {
        required: true,
        message: '请输入视频名称'
      },
    ]},
    {label: '视频简介',type:'input', name: 'remark' , span: 12 },
    {label: '适合年纪', name: 'ageId' , span: 12 ,render: () => {
      return <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择适合年纪'}
      options={dictionaries.AgeRange}
    >
    </Select>
    } },
    {label: '视频类型', name: 'videoCategoryId', span: 12 ,render:()=>{
      return  <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择类型'}
      options={dictionaries.AVType}
    >
    </Select>
    }},
    {label: '配音', name: 'dub', span: 12 ,render:()=>{
      return <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      maxTagCount={1}
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择配音'}
      options={dictionaries.isDub}
    >
    </Select>
    }},
    {label: '字幕内嵌', name: 'captionInId', span: 12 ,render:()=>{
      return <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      maxTagCount={1}
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择幕内嵌'}
      options={dictionaries.CaptionIn}
    >
    </Select>
    }},
    {label: '发行方',type:'input', name: 'publisher', span: 12 },
    {label: '视频系列', name: 'avSerialId', span: 12 ,render:()=>{
      return   <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择系列'}
      options={dictionaries.AvSerial}
    >
    </Select>
    }},
    {label: '主题', name: 'theme', span: 12 ,render:()=>{
      return   <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      mode="multiple"
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择主题'}
      options={dictionaries.Theme}
    >
    </Select>
    }},
    {label: '标签', name: 'label', span: 12 ,render:()=>{
      return  <Cascader  disabled={disabled}  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
    }},
    {label: '视频封面', name: 'pictureUrl', span: 12,render:()=>{
      return  <UploadPicture  disabled={disabled} pictureUrl={form.getFieldValue().pictureUrl} setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),pictureUrl:value})}></UploadPicture>
    }},
    {label: '上传字幕', name: 'videoSrt' , span: 12,render:()=>{
      return  <UploadSrt  disabled={disabled} srtUrl={form.getFieldValue().videoSrt} setSrt={(value)=>form.setFieldsValue({...form.getFieldValue(),videoSrt:value})}></UploadSrt>
    }},
    {label: '视频', name: 'videoUrl', span: 12,rules:[
      {
        required: true,
        message: '请上传视频'
      },
    ],render:()=>{
      return  <VideoUpload  disabled={disabled} replacePicture={(value)=>replacePicture(value)} video={form.getFieldValue().videoUrl} setVideo={(value)=>form.setFieldsValue({...form.getFieldValue(),videoUrl:value})}></VideoUpload>
    }},
    {label: '无人声视频', name: 'notVideoUrl', span: 12,render:()=>{
      return  <VideoUpload  disabled={disabled} replacePicture={(value)=>replacePicture(value)} video={form.getFieldValue().notVideoUrl} setVideo={(value)=>form.setFieldsValue({...form.getFieldValue(),notVideoUrl:value})}></VideoUpload>
    }},
  ]

  const replacePicture = (value) => {
    form.setFieldsValue({...form.getFieldValue(),pictureUrl:value})
  }

  return <div  className='info-main'>
    <LlxForm disabled={disabled} form={form} labelCol={5} formItem={newItem} />
  </div>
}
// 保存数据
const DataDialog  = (props) => {
  const {isModalVisible, setIsModalVisible,form,changeStatus,UserSpecies,userName,disabled,QandPQ} = props
  const value = statusValue(changeStatus,form.getFieldValue().videoStatus) //修改的状态

  const loading = useRef(false)

  const manager = value==='Q'||value==='PQ'?QandPQ:UserSpecies

  const [formItem] = Form.useForm();//视频详情

  const item = ['N','PN','P'].includes(value)?[
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
  ]:[
    {label: '负责人', name: 'manager' , span: 24 ,rules:[
      {
        required: true,
        message: '请选择负责人'
      },
    ],render:()=>{
      return  <Select

      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择负责人'}
      options={manager}
    >
    </Select>
    }},
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
  ]
  
 const handleCancel = () => {
    setIsModalVisible(false);
 };
 
 const handleOk = () => {
   if(loading.current) {
    message.error('请勿多次点击')
   }

  loading.current=true
  formItem.validateFields().then(async()=>{
  //  1更改状态
  await editVideoStatus({
    id: form.getFieldValue().id,
    videoStatus: value,
    qmanager: value==='Q'||value==='PQ'?formItem.getFieldValue().manager:'',
    rmanager: value==='R'||value==='PR'?formItem.getFieldValue().manager:'',
  })
   
  // 留言
  await setRemark({
    manager: formItem.getFieldValue().manager||'',
    dataId: form.getFieldValue().id,
    type: 'VIDEO',
    remark: formItem.getFieldValue().remark,
    statusNow: form.getFieldValue().videoStatus,
    statusNext: value
  })

  //  2修改数据
   if(!disabled){
   
     const editValue = form.getFieldValue()
    
    editValue.videoCategoryId=editValue.videoCategoryId?editValue.videoCategoryId:-99
      
    editValue.labels = editValue.label?editValue.label.map(i=>{
      return {id:i[1]}
      }):[]
    editValue.themes = editValue.theme?editValue.theme.map(i=>{
      return {id:i}
      }):[]


      const audio = new Audio(editValue.videoUrl)
      audio.load()
      audio.oncanplay = async() => {
        editValue.videoTime=audio.duration
         
        delete editValue.videoStatus
        delete editValue.rmanager
        delete editValue.qmanager
        delete editValue.updateTime
        delete editValue.updateBy
        delete editValue.updateTime
        delete editValue.theme
        delete editValue.label

        await addVideo(editValue)

        notification.success({
          message: '保存成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
        props.getVideoInfoFn()
        formItem.resetFields()
        setIsModalVisible(false);
      }
   } else {
    props.getVideoInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   }
  })
  loading.current=false
 }

return   <>
<Modal onOk={handleOk}  width={600} title="保存数据" visible={isModalVisible}  onCancel={handleCancel}>
      <Alert className="edit-alert" message={'你确定要修改状态至' + value + '吗？'} type="success" />

     <LlxForm form={formItem} labelCol={3} formItem={item} />
 </Modal>
</>
}


function VideoInfo(props) {

  const {examineStatus} = props
  const [isModalVisibleMore,setIsModalVisibleMore] = useState(false)
  const [isModalVisibleData,setIsModalVisibleData] = useState(false)
  const [disabled,setDisabled] = useState(false)
  const [loading,setLoading] = useState(true)
  const id = commonConfig.getUrlParams(props).id
  const [form] = Form.useForm();//视频详情
  const head = useRef()
  const [preservationJurisdiction,setPreservationJurisdiction] = useState({})
  // 1.获取数据
  useEffect(()=>{
    getVideoInfoFn()
  }, [examineStatus])// eslint-disable-line react-hooks/exhaustive-deps


  // 2.查看更多
  const getMore = () => {
    setIsModalVisibleMore(true)
  }
  // 3.保存数据
  const preservationData = () => {
   const value = statusValue(head.current.current,form.getFieldValue().videoStatus)
   if(!getStatusJurisdiction(preservationJurisdiction[0],preservationJurisdiction[1],preservationJurisdiction[2],preservationJurisdiction[3],preservationJurisdiction[4],preservationJurisdiction[5]).includes(value)) {
    notification.error({
      message: '该数据你无法保存，请联系管理员',
      description: '操作人：' + props.userInfo.user.userName,
      duration:2
    });
    return
   }
  
  // 打开弹框 输入备注 修改状态 修改数据
  setIsModalVisibleData(true)
  }
  // 4.更新数据
  const getVideoInfoFn = async () => {
    if(examineStatus){
      const res = await queryByIdVideoPublish(id)
      if(!res.result.id){
        notification.error({
          message: '该视频未发布过',
          duration:1.5
        });
        props.checkDraftDataBtn()
        setLoading(false)
        return
      }
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        label:res.result.labels?.map(i=>{
          return [i.labelCategoryId,i.id]
          }),
        theme:res.result.themes?.map(i=>i.id)
      })
      setDisabled(true)
  
      setLoading(false)
    } else {
      const res = await queryByIdVideo(id)
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        label:res.result.labels?.map(i=>{
          return [i.labelCategoryId,i.id]
          }),
        theme:res.result.themes?.map(i=>i.id)
      })
      setDisabled(!getPageJurisdiction(res.result.videoStatus,res.result.createBy,props.userInfo.user.userName))

      setPreservationJurisdiction([res.result.videoStatus,res.result.createBy,res.result.rmanager,res.result.qmanager,props.userInfo.user.userName,props.userInfo.roles.map(i => i.id).includes(7)])
     
      setLoading(false)
    }
  }

  return <div className="app-content-info animate__animated animate__fadeIn">
  {
    !loading?(
      <>
      <LlxHead examineStatus={examineStatus}  ref={head} preservationJurisdiction={preservationJurisdiction}  preservationData={preservationData} userName={props.userInfo.user.userName} role={props.userInfo.roles.map(i => i.id).includes(7)} form={form} getMore={getMore}></LlxHead>
       
       {/* 查看更多信息 */}
       <LookMore   preservationJurisdiction={preservationJurisdiction}  isModalVisible={isModalVisibleMore}  setIsModalVisible={setIsModalVisibleMore} ></LookMore>
       {/* 保存数据 */}
       <DataDialog getVideoInfoFn={getVideoInfoFn} disabled={disabled} form={form} QandPQ={props.dictionaries.QandPQ} UserSpecies={props.dictionaries.UserSpecies} userName={props.userInfo.user.userName} status={form} changeStatus={head.current?.current}   id={id} isModalVisible={isModalVisibleData} setIsModalVisible={setIsModalVisibleData} ></DataDialog>
       
       {/* 主要内容区域 */}
       {/* 1.草稿可编辑 */}
       <VideoMain form={form} dictionaries={props.dictionaries} disabled={disabled}></VideoMain>
      </>
    ):<Spin className="info-loading" tip="Loading..."></Spin>
  }
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkDraftDataBtn: () => dispatch(checkDraftData())
  }
}

export default connect((state)=>{
  return {examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(VideoInfo))